﻿using System;
using QFramework;
using UnityEngine;
using UnityEngine.UI;

namespace HareGame
{
    public class UIBase : UIPanel
    {
        protected bool m_HandleAble;//界面是否能操作
        protected ResLoader m_ResLoader;//资源加载器
        private EventID[] _events;//监听事件

        private bool m_IsInit = false;

        protected override void OnInit(IUIData uiData = null)
        {
            base.OnInit(uiData);

            m_HandleAble = true;

            m_ResLoader = ResLoader.Allocate();

            RegisterEvent();
            foreach (var v in _events)
            {
                GameEntry.Event.Register(v, DoEvent);
            }
            m_IsInit = true;

            if (Info.Level == UILevel.PopUI)
                GameEntry.Camera.EnableCameraTouch(false);
        }


        /// <summary>
        /// 注册监听事件
        /// </summary>
        /// <returns></returns>
        private void RegisterEvent()
        {
            _events = new EventID[GameEntry.GM.EventLength];
            int index = 0;
            foreach (EventID ID in Enum.GetValues(typeof(EventID)))
            {
                _events[index] = ID;
                index++;
            }
        }

        protected void PlayButtonSound()
        {
            GameEntry.Audio.PlaySound(QAssetBundle.Yx_button_mp3.YX_button);
        }

        void DoEvent(int key, params object[] param)
        {
            if (!gameObject.activeInHierarchy)
                return;

            DoEvent((EventID)key, param);
        }

        /// <summary>
        /// 执行事件
        /// </summary>
        /// <param name="eventID">事件ID</param>
        /// <param name="param">参数</param>
        protected virtual void DoEvent(EventID eventID, params object[] param)
        {

        }

        protected override void OnShow()
        {
            base.OnShow();
            m_HandleAble = true;
        }

        protected override void OnHide()
        {
            base.OnHide();
            m_HandleAble = false;
        }

        protected override void OnClose()
        {
            m_HandleAble = false;
            if (!m_IsInit)
                return;

            m_ResLoader.Recycle2Cache();
            m_ResLoader = null;

            foreach (var v in _events)
            {
                GameEntry.Event.UnRegister(v, DoEvent);
            }

            if (GameEntry.UI.GetAllPopUICount() == 0)
                GameEntry.Camera.EnableCameraTouch(true);
        }
    }
}